package com.iengoo.edu.dao.impl;

import com.iengoo.edu.config.DBConfig;
import com.iengoo.edu.dao.TicketDao;
import com.iengoo.edu.entity.Ticket;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zpym
 * @CopyRight (C) http://www.iengoo.com
 * @brief
 * @email 122162005@qq.com
 * @date 2019-01-22 15:45
 */
public class TicketDaoImpl implements TicketDao {
    @Override
    public void add(Ticket ticket) {

    }

    @Override
    public void delete(int id) {

    }

    @Override
    public void update(Ticket ticket) {

    }

    @Override
    public Ticket findById(int id) {
        return null;
    }

    @Override
    public List<Ticket> findAll() {
        // 创建存储所有ticket 对象的数组
        List<Ticket> ticketList = new ArrayList<>();
        try {
            // 加载驱动
            Class.forName(DBConfig.driver);
            // 创建链接
            Connection conn = DriverManager.getConnection(DBConfig.url, DBConfig.username, DBConfig.password);
            String sql = "SELECT * FROM ticket";
            // 创建预编译语句
            PreparedStatement ps = conn.prepareStatement(sql);
            ResultSet rs = ps.executeQuery();
            // 解析结果集
            while (rs.next()) {
                Ticket ticket = new Ticket();
                ticket.setPrice(rs.getInt("price"));
                ticket.setStartStation(rs.getString("start_station"));

                // 将对象数据放入到数组
                ticketList.add(ticket);
            }

            rs.close();
            ps.close();
            conn.close();

            // 返回数组对象
            return ticketList;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
